/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package ui.helpers;

import core.Database;
import core.DatabaseTable;
import core.TableColumn;

import ui.ApplicationWindow;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JOptionPane;
import org.apache.log4j.Logger;

/**
 *
 * @author Sakis Vtdk <sakis.vtdk@gmail.com>
 */
public class NewColumnListener implements ActionListener
{

	public NewColumnListener()
	{
	}

	@Override
	public void actionPerformed(ActionEvent evt)
	{
		this._tableId = ApplicationWindow.getApplicationWindow().getSelectedTableId();
		
		createNewColumn(_tableId);
	}

	public void createNewColumn(int tableId)
	{
		if(tableId >= 0)
		{
			String columnName = "";
			this._dbTable = Database.getDatabase().getTable(tableId);
			boolean accepted;
			do
			{
				//create a dialog to get the name of the new table
				accepted = true;
				columnName = JOptionPane.showInputDialog(null, "Enter name for the new column", "New Column", JOptionPane.PLAIN_MESSAGE);
				if(columnName != null)
				{
					try
					{
						this._dbTable.addColumn(new TableColumn(columnName));
					}
					catch(Exception e)
					{
						JOptionPane.showMessageDialog(null, "There is already a column '"+ columnName +"'. Try another.", "Error" , JOptionPane.ERROR_MESSAGE);
						log.warn("Unable to create column. There is already a column named '"+ columnName +"'. Error returned: "+ e.getMessage());
						accepted = false;
					}       
				}
				
			}while(!accepted);

			ApplicationWindow.getApplicationWindow().refreshItems();
			ApplicationWindow.getApplicationWindow().selectItemInJtree(columnName);
		}
	}

	private int _tableId;
	private DatabaseTable _dbTable;

	private static Logger log = Logger.getLogger(NewColumnListener.class);
}
